package com.jsb.laundry.controller.shops;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.aliyun.AliOSSUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 店铺邀请码
 */
@RestController
@RequestMapping("/laundryShops/")
public class ShopWxQRCodeController {

    public String getAccessToken(String appid, String secret) {
        Map map = new HashMap();
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);
        String s = HttpUtil.sendPost("https://api.weixin.qq.com/cgi-bin/stable_token", null, JSONObject.toJSONString(map));
        String accessToken = JSONObject.parseObject(s).getString("access_token");
        return accessToken;
    }

    /**
     * 获取邀请二维码
     *
     * @param param
     * @return
     */
    @PostMapping("getQRCode")
    public WebResponse QRCode(@RequestBody JSONObject param) {
        String userId = param.getString("uid"); //邀请人id
        String userType = param.getString("userType"); //用户0 ,骑手1, 店铺商家2
        String go = param.getString("go"); //0: 去用户小程序端首页,1:去骑手端首页
        if (JSBUtil.isEmptyString(userId) || JSBUtil.isEmptyString(userType) || JSBUtil.isEmptyString(go)) {
            return WebResponse.failOfParameter();
        }
        String accessToken;
        JSONObject jsonStr = new JSONObject();
        if ("0".equals(go)) { // 用户小程序端 AccessToken  0:去用户小程序端首页1:去骑手端首页
            accessToken = getAccessToken("wxb730137b1ae9f679", "86fcb97161a0ea96bc082f3b58d0e8ed");
            jsonStr.put("path", String.format("/pages/clothes/index?userId=%s&userType=%s", userId, userType));
        } else {
            accessToken = getAccessToken("wx66259c2db83de8c2", "a751a2d916092083cbd85d4f58ffc0b5");
            jsonStr.put("path", String.format("/pages/mytask/index?userId=%s&userType=%s", userId, userType));
        }
        String code = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
        jsonStr.put("width", "280px");
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(code);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)   //连接服务区主机超时时间
                .setConnectionRequestTimeout(60000) //连接请求超时时间
                .setSocketTimeout(60000).build(); //设置读取响应数据超时时间
        //为httppost请求设置参数
        httpPost.setConfig(requestConfig);
        //将上传参数放到entity属性中
        httpPost.setEntity(new StringEntity(JSON.toJSONString(jsonStr), "UTF-8"));
        //添加头信息
        httpPost.addHeader("Content-type", "text/xml");
        String result = "";
        String resCodeImg = null;
        try {
            //发送请求
            httpResponse = httpClient.execute(httpPost);
            //从相应对象中获取返回内容
            HttpEntity entity = httpResponse.getEntity();
            InputStream content = entity.getContent();
            byte[] bytes = InputStreamToByte(content);
            result = Base64.encodeBase64String(bytes);

            MultipartFile multipartFile = base64ToMultipartFile(result);
            resCodeImg = AliOSSUtil.uploadFile(multipartFile, "code");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return WebResponse.successData(resCodeImg);
    }

    public static MultipartFile base64ToMultipartFile(String base64String) throws IOException {
        byte[] content = Base64.decodeBase64(base64String);
        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "file", "shopWechatQRCodeBase64Str.png", ContentType.APPLICATION_OCTET_STREAM.toString(), content);
        return mockMultipartFile;
    }

    /**
     * 输入流转字节流
     */
    private byte[] InputStreamToByte(InputStream in) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int ch;
        while ((ch = in.read(buffer)) != -1) {
            bytestream.write(buffer, 0, ch);
        }
        byte data[] = bytestream.toByteArray();
        bytestream.close();
        return data;
    }

}
